﻿using BitShuva.Models;
using BitShuva.Common;
using Raven.Client;
using Raven.Client.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace BitShuva.Controllers
{
    public abstract class UserContextController : RavenApiController
    {
        protected async Task<User> GetUserOrNull()
        {
            var userCookie = HttpContext.Current.Request.Cookies["userId"];
            if (userCookie != null)
            {
                return await this.Session.LoadAsync<User>(userCookie.Value);
            }

            return null;
        }

        protected async Task<Song> GetSongDto(Song song)
        {
            var user = await this.GetUserOrNull();
            if (user != null)
            {
                var songLike = await this.Session
                        .Query<Like>()
                        .Customize(c => c.Include<Like>(l => l.SongId))
                        .FirstOrDefaultAsync(s => s.UserId == user.Id && s.SongId == song.Id);

                return song.ToDto(songLike.StatusOrNone());
            }

            return song.ToDto();
        }

        protected void EnsureIsAdminUser()
        {
            // TODO: throw if not admin user.
        }
    }
}
